{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.environ['CUDA_VISIBLE_DEVICES'] = '3'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "import json"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('dataset-bpe.json') as fopen:\n",
    "    data = json.load(fopen)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_X = data['train_X']\n",
    "train_Y = data['train_Y']\n",
    "test_X = data['test_X']\n",
    "test_Y = data['test_Y']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "EOS = 2\n",
    "GO = 1\n",
    "vocab_size = 32000"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_Y = [i + [2] for i in train_Y]\n",
    "test_Y = [i + [2] for i in test_Y]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import beam_search\n",
    "\n",
    "def pad_second_dim(x, desired_size):\n",
    "    padding = tf.tile([[[0.0]]], tf.stack([tf.shape(x)[0], desired_size - tf.shape(x)[1], tf.shape(x)[2]], 0))\n",
    "    return tf.concat([x, padding], 1)\n",
    "\n",
    "class Translator:\n",
    "    def __init__(self, size_layer, num_layers, embedded_size, learning_rate):\n",
    "        \n",
    "        def cells(reuse=False):\n",
    "            return tf.nn.rnn_cell.LSTMCell(size_layer,initializer=tf.orthogonal_initializer(),reuse=reuse)\n",
    "        \n",
    "        def attention(encoder_out, seq_len, reuse=False):\n",
    "            attention_mechanism = tf.contrib.seq2seq.BahdanauAttention(num_units = size_layer, \n",
    "                                                                    memory = encoder_out,\n",
    "                                                                    memory_sequence_length = seq_len)\n",
    "            return tf.contrib.seq2seq.AttentionWrapper(\n",
    "            cell = tf.nn.rnn_cell.MultiRNNCell([cells(reuse) for _ in range(num_layers)]), \n",
    "                attention_mechanism = attention_mechanism,\n",
    "                attention_layer_size = size_layer)\n",
    "        \n",
    "        self.X = tf.placeholder(tf.int32, [None, None])\n",
    "        self.Y = tf.placeholder(tf.int32, [None, None])\n",
    "        \n",
    "        self.X_seq_len = tf.count_nonzero(self.X, 1, dtype = tf.int32)\n",
    "        self.Y_seq_len = tf.count_nonzero(self.Y, 1, dtype = tf.int32)\n",
    "        batch_size = tf.shape(self.X)[0]\n",
    "        \n",
    "        embeddings = tf.Variable(tf.random_uniform([vocab_size, embedded_size], -1, 1))\n",
    "        \n",
    "        encoder_out, encoder_state = tf.nn.dynamic_rnn(\n",
    "            cell = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)]), \n",
    "            inputs = tf.nn.embedding_lookup(embeddings, self.X),\n",
    "            sequence_length = self.X_seq_len,\n",
    "            dtype = tf.float32)\n",
    "        main = tf.strided_slice(self.Y, [0, 0], [batch_size, -1], [1, 1])\n",
    "        decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n",
    "        dense = tf.layers.Dense(vocab_size)\n",
    "        decoder_cells = attention(encoder_out, self.X_seq_len)\n",
    "        \n",
    "        states = decoder_cells.zero_state(batch_size, tf.float32).clone(cell_state=encoder_state)\n",
    "        \n",
    "        training_helper = tf.contrib.seq2seq.TrainingHelper(\n",
    "                inputs = tf.nn.embedding_lookup(embeddings, decoder_input),\n",
    "                sequence_length = self.Y_seq_len,\n",
    "                time_major = False)\n",
    "        training_decoder = tf.contrib.seq2seq.BasicDecoder(\n",
    "                cell = decoder_cells,\n",
    "                helper = training_helper,\n",
    "                initial_state = states,\n",
    "                output_layer = dense)\n",
    "        training_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n",
    "                decoder = training_decoder,\n",
    "                impute_finished = True,\n",
    "                maximum_iterations = tf.reduce_max(self.Y_seq_len))\n",
    "        self.training_logits = training_decoder_output.rnn_output\n",
    "        \n",
    "        predicting_helper = tf.contrib.seq2seq.GreedyEmbeddingHelper(\n",
    "                embedding = embeddings,\n",
    "                start_tokens = tf.tile(tf.constant([GO], dtype=tf.int32), [batch_size]),\n",
    "                end_token = EOS)\n",
    "        predicting_decoder = tf.contrib.seq2seq.BasicDecoder(\n",
    "                cell = decoder_cells,\n",
    "                helper = predicting_helper,\n",
    "                initial_state = states,\n",
    "                output_layer = dense)\n",
    "        predicting_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n",
    "                decoder = predicting_decoder,\n",
    "                impute_finished = True,\n",
    "                maximum_iterations = 2 * tf.reduce_max(self.X_seq_len))\n",
    "        self.fast_result = predicting_decoder_output.sample_id\n",
    "        \n",
    "        masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n",
    "        self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.training_logits,\n",
    "                                                     targets = self.Y,\n",
    "                                                     weights = masks)\n",
    "        self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n",
    "        y_t = tf.argmax(self.training_logits,axis=2)\n",
    "        y_t = tf.cast(y_t, tf.int32)\n",
    "        self.prediction = tf.boolean_mask(y_t, masks)\n",
    "        mask_label = tf.boolean_mask(self.Y, masks)\n",
    "        correct_pred = tf.equal(self.prediction, mask_label)\n",
    "        correct_index = tf.cast(correct_pred, tf.float32)\n",
    "        self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "size_layer = 512\n",
    "num_layers = 2\n",
    "embedded_size = 256\n",
    "learning_rate = 1e-3\n",
    "batch_size = 128\n",
    "epoch = 20"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/util/deprecation.py:507: calling count_nonzero (from tensorflow.python.ops.math_ops) with axis is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "reduction_indices is deprecated, use axis instead\n",
      "WARNING:tensorflow:From <ipython-input-8-e32dc117de08>:11: LSTMCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "This class is equivalent as tf.keras.layers.LSTMCell, and will be replaced by that in Tensorflow 2.0.\n",
      "WARNING:tensorflow:From <ipython-input-8-e32dc117de08>:32: MultiRNNCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "This class is equivalent as tf.keras.layers.StackedRNNCells, and will be replaced by that in Tensorflow 2.0.\n",
      "WARNING:tensorflow:From <ipython-input-8-e32dc117de08>:35: dynamic_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `keras.layers.RNN(cell)`, which is equivalent to this API\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:958: Layer.add_variable (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `layer.add_weight` method instead.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:962: calling Zeros.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Call initializer instance with the dtype argument instead of passing it to the constructor\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn.py:244: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use tf.where in 2.0, which has the same broadcast rule as np.where\n",
      "WARNING:tensorflow:\n",
      "The TensorFlow contrib module will not be included in TensorFlow 2.0.\n",
      "For more information, please see:\n",
      "  * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md\n",
      "  * https://github.com/tensorflow/addons\n",
      "  * https://github.com/tensorflow/io (for I/O related ops)\n",
      "If you depend on functionality not listed there, please file an issue.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "tf.reset_default_graph()\n",
    "sess = tf.InteractiveSession()\n",
    "model = Translator(size_layer, num_layers, embedded_size, learning_rate)\n",
    "sess.run(tf.global_variables_initializer())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "pad_sequences = tf.keras.preprocessing.sequence.pad_sequences"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[array([[29723, 29723, 23181, 23181, 29268,  4585, 29268, 29268, 16742,\n",
       "         16742, 16742, 24199,  1312,  1312, 10641, 10641, 10641, 10641,\n",
       "         29719, 30530, 30530, 30530,  5436, 14157, 14157, 14157, 16840,\n",
       "         16840, 16840, 25082, 18035,  4266, 19400, 19400, 19400, 19400,\n",
       "         19400,  1148,  1148,  1148, 17393, 22315, 22315, 13996,  2580,\n",
       "         25967, 25967, 25967, 17342, 17342, 17342, 17342, 21829, 21829,\n",
       "         21829, 21829, 21829, 21829, 22869, 26436, 26436, 26436, 26436,\n",
       "         24282, 24282, 29652, 29652, 29723, 29723, 29723,  6952,  6952],\n",
       "        [ 8351,  5191,  5191, 13356, 13356, 27006, 27006, 27006,  5260,\n",
       "          5260,  5260, 28490, 28490,  6496, 19141,    10,    10,    10,\n",
       "          8926,  8926,  8926,   937,  3960,  3960,  7688,  4137,  4137,\n",
       "          4137,   864,   864, 15733, 15733, 15733,  1055, 11341, 11341,\n",
       "         11341, 11341, 11341,  9648, 26148,   216,   216,  5074,  9648,\n",
       "         31336, 31336,  9648, 21286, 21286, 21286, 21286, 21286, 27056,\n",
       "         27056, 15054, 15054,  4228, 15054, 15054,  3265,  3265, 10387,\n",
       "         14249, 29939, 29939, 29939, 29939, 11016, 11016, 11016,  9941],\n",
       "        [26073, 28928,  8404,  8404, 31741, 31741, 17452, 17452,  2586,\n",
       "          2586, 31829, 12656, 12656, 12656,  2703, 14069, 27348, 27348,\n",
       "         27348, 27348,  1839,  1839,  5554,  5554,  5554,  8612,  8612,\n",
       "          8612, 27035, 27035, 27035, 27035, 27035,  2626,  2626,  2626,\n",
       "          2626, 23731, 18394, 18394,  1446,  1446,  1446,  1446, 16717,\n",
       "         11024, 11024,  6605, 17412, 17412, 17412, 17412,  2429, 26959,\n",
       "          7882, 20362, 20362, 18713, 18713, 18713,   612, 23140, 23140,\n",
       "          1175,  1175, 22776, 20924, 20924, 22776, 17461, 17461, 22776],\n",
       "        [31144, 18145, 26490, 26490, 12937, 12937, 29833, 29833, 30406,\n",
       "         18186, 12713, 18186, 18186, 29413, 29413, 13940, 13940, 13940,\n",
       "         25893, 25893, 25893, 25893, 14157, 14157, 14157,  1294,  1294,\n",
       "         13122, 13122, 13122, 13122, 13122, 15741,  9096, 10108,  3381,\n",
       "          6426,  6426,  6426,  6426,  6426,  6426,  1761,  1761,  1761,\n",
       "          1761,  6473,  6473, 12959, 12959, 12959,  4000,  4000,  4000,\n",
       "          4000,  4000,  4000,  4000,  4000,  4000,  4648, 29397, 29397,\n",
       "         29397, 14070, 14070, 14070, 14070, 14070, 14070,  9867,  9867],\n",
       "        [14859, 24553, 24553,   569,   569,  3872,  3872, 18800, 18800,\n",
       "         13599, 13599, 18735, 18735, 25262, 24171,  7671,  7671,  7671,\n",
       "          9569,  9569, 29624,  9569, 31084, 31084, 31084,  1805, 14622,\n",
       "         31867, 21916, 14622, 14622, 16638, 16638, 12522, 12522, 12522,\n",
       "         30494, 21274,  2076,  2976,  2976, 25971, 15392, 22784, 18053,\n",
       "           721,   721, 21517, 28990,  6378,  6378,  1847,  1847,  1847,\n",
       "          1847, 23533, 23533, 23533, 23533, 23533, 31781, 29435, 29435,\n",
       "         29435, 25322, 25322, 28046, 28046, 30767, 30767, 16723, 16723],\n",
       "        [ 6348,  6348,  6348,  6348, 20722, 14319, 28185, 28185, 28185,\n",
       "         28185, 25672, 25672, 25672, 25672, 29537, 29537, 15580, 24610,\n",
       "         24610,   350, 26668, 26668,   350,   350, 26668,  8395,  8395,\n",
       "         14067,  1165,  1165,  1165, 29945, 29945, 29945,  6626,  6218,\n",
       "          6218,  6218,  6218,  6218,  6218, 11444, 23634, 11444, 27653,\n",
       "         27653, 11444, 18022, 18022, 26386,  9044,  9044,  9044, 21163,\n",
       "         13393,  3978,  3978, 30170, 30170, 30170, 17659, 17659, 17659,\n",
       "         18290, 18290, 12625, 14170, 17551, 17551,  4897,  1692,  4897],\n",
       "        [ 7941,  7744,  7744,   409,   409,   409,  8595,  8595,  8595,\n",
       "          8595,  1487,  1487,  1487, 12907, 25911, 25911, 10814, 10814,\n",
       "         10814, 14761, 14761, 14761, 14761, 11468, 11468, 29101, 24146,\n",
       "         24146, 24146,  3731,  3731,  3731,  3731, 25589, 25589, 25589,\n",
       "         25589, 25589, 25589, 29540,  8716,  8716,  8716,  2809, 25208,\n",
       "          2809, 25208,  6875,  6875,  6875,  5466,  5466, 10367,  1731,\n",
       "          1731,  1731,  1731, 19281, 31850, 31850, 31850, 26881,  4581,\n",
       "          4581,  4581,  4940,  4940, 28660, 25482, 26545, 26545, 19281],\n",
       "        [29164, 13273, 16725, 10716, 13496, 13496, 20769, 20769, 12844,\n",
       "          8927,  8927,  3878,  3878,  3878,  3878,  3878, 23067, 23067,\n",
       "         23067,  8690,  8690, 27371, 27371, 27371, 27371,    32,    32,\n",
       "         25858, 25858, 25858, 25858, 12959, 23718, 23718, 23718, 23630,\n",
       "         23630, 19574, 19574, 19574, 19574,  1104,  1104,  1104, 10251,\n",
       "         10251, 10251, 10251, 10251, 10311, 10311, 10311,  1621,  1621,\n",
       "          1621, 23053, 23053, 23511, 23511,   771,  6120, 18422, 18422,\n",
       "          1961,  1961,  1961,  1961, 24975, 19929, 27007,  6630,  6630],\n",
       "        [17853, 21023, 21023,  7339,  7339,  7339, 22928, 22928, 22928,\n",
       "         12902, 12902, 16564, 16564, 20089, 20089, 11980, 11980, 17462,\n",
       "         17462, 17462, 13544, 13544, 25360, 25360, 25360, 25360, 21353,\n",
       "         21353, 21353, 21353, 16010, 16010,  4963,  4963,  4963,  8733,\n",
       "          8733, 22476, 22476,  4339,  4339, 22578, 19067, 29544,  3842,\n",
       "         19936, 19936, 19936, 19936,  2252,  5976,  5976, 28212, 17417,\n",
       "         12989, 12989,  6439,  1053,  1053,  1053,  1053,  5871, 14363,\n",
       "         22868, 19232, 18035, 12293,   435,   435, 31549, 31549, 31549],\n",
       "        [24580, 30924, 29205, 29205, 12959, 21872,  9141,  9141,  3611,\n",
       "          3611, 21876, 21876,  2699,  2699,  2699, 18109, 21493, 21493,\n",
       "         19706, 19706,  7460,  7460, 14298, 14298, 14298, 14298, 14298,\n",
       "         14298,  3362, 18401,  3362,  3362, 15856,  7536,  9027,  9027,\n",
       "          9027, 16488, 16488, 31673, 31673, 10712, 22869, 12742, 12742,\n",
       "         31356,  1773,  1773, 25638, 25638, 25638, 11952, 30649, 21020,\n",
       "         21020, 21020, 21020, 12736, 12736, 12736, 12736, 12736, 12736,\n",
       "         12736, 20227, 20227, 20227, 12466, 12466, 12466, 12466, 26671]],\n",
       "       dtype=int32), 10.373332, 0.0]"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "batch_x = pad_sequences(train_X[:10], padding='post')\n",
    "batch_y = pad_sequences(train_Y[:10], padding='post')\n",
    "\n",
    "sess.run([model.fast_result, model.cost, model.accuracy], \n",
    "         feed_dict = {model.X: batch_x, model.Y: batch_y})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:11<00:00,  2.33it/s, accuracy=0.327, cost=4.09]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.97it/s, accuracy=0.382, cost=3.64]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 1, training avg loss 5.288990, training avg acc 0.220226\n",
      "epoch 1, testing avg loss 3.908885, testing avg acc 0.356495\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:23<00:00,  2.29it/s, accuracy=0.472, cost=2.93]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.95it/s, accuracy=0.522, cost=2.7] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 2, training avg loss 3.350596, training avg acc 0.422510\n",
      "epoch 2, testing avg loss 3.024520, testing avg acc 0.464871\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:25<00:00,  2.28it/s, accuracy=0.536, cost=2.39]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.95it/s, accuracy=0.575, cost=2.44]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 3, training avg loss 2.703911, training avg acc 0.499716\n",
      "epoch 3, testing avg loss 2.730047, testing avg acc 0.501932\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:25<00:00,  2.28it/s, accuracy=0.589, cost=2.04]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.95it/s, accuracy=0.597, cost=2.31]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 4, training avg loss 2.355016, training avg acc 0.543313\n",
      "epoch 4, testing avg loss 2.624124, testing avg acc 0.516157\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:25<00:00,  2.28it/s, accuracy=0.645, cost=1.72]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.96it/s, accuracy=0.586, cost=2.25]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 5, training avg loss 2.105353, training avg acc 0.576615\n",
      "epoch 5, testing avg loss 2.579863, testing avg acc 0.525650\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:24<00:00,  2.28it/s, accuracy=0.682, cost=1.48]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.95it/s, accuracy=0.581, cost=2.3] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 6, training avg loss 1.912664, training avg acc 0.603643\n",
      "epoch 6, testing avg loss 2.609407, testing avg acc 0.527636\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:24<00:00,  2.28it/s, accuracy=0.712, cost=1.27]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.93it/s, accuracy=0.602, cost=2.26]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 7, training avg loss 1.749356, training avg acc 0.627599\n",
      "epoch 7, testing avg loss 2.642000, testing avg acc 0.528792\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:27<00:00,  2.27it/s, accuracy=0.748, cost=1.1] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.95it/s, accuracy=0.597, cost=2.26]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 8, training avg loss 1.609038, training avg acc 0.648796\n",
      "epoch 8, testing avg loss 2.717720, testing avg acc 0.524698\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:20<00:00,  2.30it/s, accuracy=0.775, cost=0.954]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.94it/s, accuracy=0.597, cost=2.37]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 9, training avg loss 1.488486, training avg acc 0.667919\n",
      "epoch 9, testing avg loss 2.800117, testing avg acc 0.518836\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:24<00:00,  2.28it/s, accuracy=0.792, cost=0.84]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.93it/s, accuracy=0.591, cost=2.36]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 10, training avg loss 1.378106, training avg acc 0.686154\n",
      "epoch 10, testing avg loss 2.879417, testing avg acc 0.518442\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:25<00:00,  2.28it/s, accuracy=0.82, cost=0.763]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.93it/s, accuracy=0.575, cost=2.48]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 11, training avg loss 1.272139, training avg acc 0.704506\n",
      "epoch 11, testing avg loss 2.962424, testing avg acc 0.511510\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:25<00:00,  2.28it/s, accuracy=0.836, cost=0.675]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.97it/s, accuracy=0.565, cost=2.57]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 12, training avg loss 1.185149, training avg acc 0.719297\n",
      "epoch 12, testing avg loss 3.071006, testing avg acc 0.507513\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:23<00:00,  2.29it/s, accuracy=0.855, cost=0.603]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.99it/s, accuracy=0.586, cost=2.66]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 13, training avg loss 1.112766, training avg acc 0.731863\n",
      "epoch 13, testing avg loss 3.167201, testing avg acc 0.505265\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:27<00:00,  2.27it/s, accuracy=0.868, cost=0.533]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.97it/s, accuracy=0.591, cost=2.65]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 14, training avg loss 1.044994, training avg acc 0.744048\n",
      "epoch 14, testing avg loss 3.260137, testing avg acc 0.503894\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:24<00:00,  2.28it/s, accuracy=0.875, cost=0.507]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.96it/s, accuracy=0.554, cost=2.81]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 15, training avg loss 0.983236, training avg acc 0.755417\n",
      "epoch 15, testing avg loss 3.356666, testing avg acc 0.500829\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:26<00:00,  2.28it/s, accuracy=0.884, cost=0.446]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.94it/s, accuracy=0.57, cost=2.77] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 16, training avg loss 0.915208, training avg acc 0.768989\n",
      "epoch 16, testing avg loss 3.454101, testing avg acc 0.499869\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:25<00:00,  2.28it/s, accuracy=0.881, cost=0.469]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.99it/s, accuracy=0.591, cost=2.98]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 17, training avg loss 0.874188, training avg acc 0.776034\n",
      "epoch 17, testing avg loss 3.527267, testing avg acc 0.493723\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:24<00:00,  2.28it/s, accuracy=0.892, cost=0.415]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.96it/s, accuracy=0.602, cost=3.1] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 18, training avg loss 0.830410, training avg acc 0.784509\n",
      "epoch 18, testing avg loss 3.642316, testing avg acc 0.489114\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:22<00:00,  2.29it/s, accuracy=0.902, cost=0.362]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.97it/s, accuracy=0.554, cost=3.27]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 19, training avg loss 0.772868, training avg acc 0.797126\n",
      "epoch 19, testing avg loss 3.740390, testing avg acc 0.487163\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:22<00:00,  2.29it/s, accuracy=0.899, cost=0.375]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.16it/s, accuracy=0.581, cost=3.4] "
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 20, training avg loss 0.737197, training avg acc 0.804053\n",
      "epoch 20, testing avg loss 3.893038, testing avg acc 0.487759\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "import tqdm\n",
    "\n",
    "for e in range(epoch):\n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(train_X), batch_size), desc = 'minibatch loop')\n",
    "    train_loss, train_acc, test_loss, test_acc = [], [], [], []\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(train_X))\n",
    "        batch_x = pad_sequences(train_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(train_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y}\n",
    "        accuracy, loss, _ = sess.run([model.accuracy,model.cost,model.optimizer],\n",
    "                                    feed_dict = feed)\n",
    "        train_loss.append(loss)\n",
    "        train_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    \n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(test_X), batch_size), desc = 'minibatch loop')\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(test_X))\n",
    "        batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(test_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y,}\n",
    "        accuracy, loss = sess.run([model.accuracy,model.cost],\n",
    "                                    feed_dict = feed)\n",
    "\n",
    "        test_loss.append(loss)\n",
    "        test_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    print('epoch %d, training avg loss %f, training avg acc %f'%(e+1,\n",
    "                                                                 np.mean(train_loss),np.mean(train_acc)))\n",
    "    print('epoch %d, testing avg loss %f, testing avg acc %f'%(e+1,\n",
    "                                                              np.mean(test_loss),np.mean(test_acc)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import bleu_hook"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 40/40 [00:19<00:00,  2.09it/s]\n"
     ]
    }
   ],
   "source": [
    "results = []\n",
    "for i in tqdm.tqdm(range(0, len(test_X), batch_size)):\n",
    "    index = min(i + batch_size, len(test_X))\n",
    "    batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "    feed = {model.X: batch_x}\n",
    "    p = sess.run(model.fast_result,feed_dict = feed)\n",
    "    result = []\n",
    "    for row in p:\n",
    "        result.append([i for i in row if i > 3])\n",
    "    results.extend(result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    "rights = []\n",
    "for r in test_Y:\n",
    "    rights.append([i for i in r if i > 3])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.15275387"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "bleu_hook.compute_bleu(reference_corpus = rights,\n",
    "                       translation_corpus = results)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
